package org.zhangkun.jmsg.bean;

import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;

import org.zhangkun.jmsg.core.network.exception.DataPackageParseException;

/**
 * 解包数据
 * 
 * @author zhangkun
 * 
 */
public class DataUnPack extends DataPackage {

	private int port;

	/**
	 * 根据自己构建一个响应包
	 * 
	 * @return
	 */
	public DataPack getDataPack() {
		DataPack dp = new DataPack();
		dp.setDataID(this.getDataID());
		dp.setSendToHostAddres(getSenderHostAddres());
		dp.setSendToHostName(getSenderHostName());
		// dp.setSenderName(senderName);
		return dp;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	/**
	 * 解析一个包
	 * 
	 * @param dp
	 * @throws DataPackageParseException
	 */
	public void unPack(DatagramPacket dp) throws DataPackageParseException {
		String[] s = new String(dp.getData()).split(":", 6);
		this.setSenderHostAddres(dp.getAddress().getHostAddress());
		this.setVersion(s[0]);
		this.setDataID(s[1]);
		this.setSenderName(s[2]);
		this.setSenderHostName(s[3]);
		this.setPort(dp.getPort());
		if (s.length == 6)
			this.setMsg(s[5]);
		try {
			this.setDataType(Long.parseLong(s[4]));
		} catch (Exception e) {
			throw new DataPackageParseException(e);
		}
		// if (getDataType() == 6291459L)
		// if (s.length == 6)
		// this.setSenderName(s[5]);
		System.out.println(getMsg());

	}

	/**
	 * 指定编码解析一个包
	 * 
	 * @param dp
	 * @throws DataPackageParseException
	 */
	public void unPack(DatagramPacket dp, String encoding)
			throws DataPackageParseException {
		String[] s;
		try {
			s = new String(dp.getData(), encoding).split("\\:", 6);
			if (s.length < 6)
				throw new DataPackageParseException();
			this.setSenderHostAddres(dp.getAddress().getHostAddress());
			this.setVersion(s[0].trim());
			this.setDataID(s[1].trim());
			this.setSenderName(s[2].trim());
			this.setSenderHostName(s[3].trim());
			if (s.length == 6)
				this.setMsg(s[5].trim());
			try {
				this.setDataType(Long.parseLong(s[4]));
			} catch (Exception e) {
				throw new DataPackageParseException(e);
			}
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			unPack(dp);
		}
	}

	public void unPack(String msg) throws DataPackageParseException {
		String[] s;

		s = msg.split("\\:", 6);
		if (s.length < 6)
			throw new DataPackageParseException();
		// this.setSenderHostAddres(dp.getAddress().getHostAddress());
		this.setVersion(s[0].trim());
		this.setDataID(s[1].trim());
		this.setSenderName(s[2].trim());
		this.setSenderHostName(s[3].trim());
		if (s.length == 6)
			this.setMsg(s[5].trim());
		try {
			this.setDataType(Long.parseLong(s[4]));
		} catch (Exception e) {
			throw new DataPackageParseException(e);
		}

	}

}
